<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能问答 - DocuGen</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="/static/css/common.css">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="bi bi-file-earmark-text me-2"></i>DocuGen
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/"><i class="bi bi-house me-1"></i>首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/document-generator"><i class="bi bi-file-earmark-text me-1"></i>文档生成</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/template-generator"><i class="bi bi-file-earmark-richtext me-1"></i>模板生成</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/qa"><i class="bi bi-chat-dots me-1"></i>智能问答</a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="modelDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-gear me-1"></i>模型设置
                        </a>
                        <ul class="dropdown-menu" aria-labelledby="modelDropdown">
                            <li><a class="dropdown-item model-switch" data-model="local" href="#"><i class="bi bi-cpu me-1"></i>本地模型</a></li>
                            <li><a class="dropdown-item model-switch" data-model="third_party" href="#"><i class="bi bi-cloud me-1"></i>第三方模型</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="main-content">
        <div class="container py-4">
            <div class="page-header">
                <h1 class="page-title"><i class="bi bi-chat-dots"></i>智能问答</h1>
            </div>
            
            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-header bg-primary text-white">
                            <h5 class="card-title">
                                <i class="bi bi-chat-square-text me-2"></i>
                                智能对话
                            </h5>
                        </div>
                        <div class="card-body">
                            <!-- RAG选项 -->
                            <div class="rag-options">
                                <h6 class="rag-options-title">
                                    <div class="feature-icon">
                                        <i class="bi bi-database"></i>
                                    </div>
                                    知识库增强
                                </h6>
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" id="useRag" checked>
                                    <label class="form-check-label" for="useRag">
                                        使用RAG增强回答质量
                                    </label>
                                </div>
                                <div class="row">
                                    <div class="col-md-8">
                                        <select class="form-select" id="ragSource" disabled>
                                            <option value="">加载知识库中...</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <button class="btn btn-outline-primary w-100" id="refreshKbBtn">
                                            <i class="bi bi-arrow-clockwise"></i>刷新列表
                                        </button>
                                    </div>
                                </div>
                                <div class="mt-3" id="customRagSection" style="display: none;">
                                    <textarea class="form-control" id="customRagInput" rows="2" placeholder="输入自定义知识库内容，用于增强回答质量"></textarea>
                                </div>
                            </div>
                            
                            <div class="chat-container mb-4" id="chatContainer">
                                <div class="message assistant-message">
                                    <div class="message-avatar assistant-avatar">
                                        <i class="bi bi-robot"></i>
                                    </div>
                                    您好！我是DocuGen智能助手，请问有什么可以帮您？
                                </div>
                            </div>
                            <div class="input-group">
                                <input type="text" class="form-control" id="userInput" placeholder="请输入您的问题...">
                                <button class="btn btn-primary" type="button" id="sendButton">
                                    <i class="bi bi-send"></i>发送
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer class="text-white py-4">
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <h5><i class="bi bi-file-earmark-text me-2"></i>DocuGen</h5>
                    <p>AI驱动的文档生成系统，让创作更高效。</p>
                </div>
                <div class="col-md-6 text-md-end">
                    <p class="mb-0">&copy; 2023 DocuGen. 保留所有权利。</p>
                </div>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            let currentModel = 'third_party';
            
            // 加载知识库列表
            loadKnowledgeBases();
            
            // 知识库选择逻辑
            $('#useRag').on('change', function() {
                const useRag = $(this).is(':checked');
                $('#ragSource').prop('disabled', !useRag);
                
                // 如果选择了自定义知识库，显示自定义内容输入框
                if (useRag && $('#ragSource').val() === 'custom') {
                    $('#customRagSection').show();
                } else {
                    $('#customRagSection').hide();
                }
            });
            
            // RAG相关事件处理
            $('#ragSource').on('change', function() {
                const isCustom = $(this).val() === 'custom';
                $('#customRagSection').toggle(isCustom);
            });
            
            // 刷新知识库列表
            $('#refreshKbBtn').on('click', function() {
                loadKnowledgeBases();
            });
            
            // 加载知识库列表函数
            function loadKnowledgeBases() {
                $.ajax({
                    url: '/api/kb/list',
                    type: 'GET',
                    success: function(response) {
                        if (response.success && response.data) {
                            const $select = $('#ragSource');
                            $select.empty();
                            
                            // 添加自定义选项
                            $select.append('<option value="custom">自定义知识库内容</option>');
                            
                            // 添加知识库选项
                            if (Array.isArray(response.data)) {
                                if (response.data.length > 0) {
                                    response.data.forEach(function(kb) {
                                        // 直接使用kb作为值和显示文本，因为后端已经处理好了格式
                                        $select.append(`<option value="${kb}">${kb}</option>`);
                                    });
                                    console.log("成功加载知识库列表:", response.data);
                                } else {
                                    console.log("知识库列表为空");
                                    $select.append('<option value="">没有可用的知识库</option>');
                                }
                            } else {
                                console.error("知识库数据格式错误:", response.data);
                                $select.append('<option value="">数据格式错误</option>');
                            }
                            
                            // 启用选择框
                            $select.prop('disabled', !$('#useRag').is(':checked'));
                        } else {
                            console.error("获取知识库列表失败:", response);
                            $('#ragSource').html('<option value="">加载知识库失败</option>');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("请求知识库列表失败:", status, error);
                        $('#ragSource').html('<option value="">加载知识库失败</option>');
                    }
                });
            }
            
            // 发送消息
            function sendMessage() {
                const userInput = $('#userInput').val().trim();
                if (!userInput) return;
                
                // 添加用户消息
                appendMessage('user', userInput);
                $('#userInput').val('');
                
                // 准备请求数据
                const useRag = $('#useRag').is(':checked');
                const ragSource = useRag ? $('#ragSource').val() : '';
                const customRagContent = (useRag && ragSource === 'custom') ? $('#customRagInput').val().trim() : '';
                
                // 添加思考中的消息
                const loadingMessageId = 'loading-' + Date.now();
                appendMessage('assistant', '<div class="typing-indicator"><span></span><span></span><span></span></div>', loadingMessageId);
                
                // 构建查询参数
                const params = new URLSearchParams({
                    message: userInput
                });
                
                if (useRag) {
                    params.append('enable_rag', 'true');
                    if (ragSource) {
                        params.append('kb_name', ragSource);
                    }
                    if (ragSource === 'custom' && customRagContent) {
                        params.append('custom_rag_content', customRagContent);
                    }
                }
                
                // 发送流式请求
                let eventSource;
                try {
                    console.log("创建EventSource连接...");
                    console.log("请求URL:", `/api/chat/stream?${params.toString()}`);
                    
                    eventSource = new EventSource(`/api/chat/stream?${params.toString()}`);
                    
                    let responseText = '';
                    
                    eventSource.onopen = function() {
                        console.log("EventSource连接已打开");
                    };
                    
                    eventSource.onmessage = function(event) {
                        try {
                            console.log("收到消息:", event.data);
                            
                            // 检查是否是结束标记
                            if (event.data === '[DONE]') {
                                console.log("收到结束标记，关闭连接");
                                eventSource.close();
                                return;
                            }
                            
                            const data = JSON.parse(event.data);
                            
                            if (data.thinking) {
                                // 显示思考中状态
                                $(`#${loadingMessageId}`).html('<div class="typing-indicator"><span></span><span></span><span></span></div>');
                                return;
                            } else if (data.content) {
                                responseText = data.content; // 替换而不是追加，因为服务器发送的是完整内容
                                console.log("更新消息内容");
                                // 更新消息内容
                                $(`#${loadingMessageId}`).html(responseText);
                            } else if (data.references && data.references.length > 0) {
                                // 添加参考信息
                                console.log("添加参考信息:", data.references);
                                let referencesHtml = `
                                    <div class="references-section mt-3">
                                        <div class="references-header">
                                            <div><i class="bi bi-book me-2"></i>参考资料 (${data.references.length})</div>
                                        </div>
                                        <div class="references-list">
                                `;
                                
                                data.references.forEach(function(ref, index) {
                                    referencesHtml += `
                                        <div class="reference-item">
                                            <div class="reference-title">${ref.title || `参考 ${index+1}`}</div>
                                            <div class="reference-content">${ref.content || ""}</div>
                                        </div>
                                    `;
                                });
                                
                                referencesHtml += `
                                        </div>
                                    </div>
                                `;
                                
                                // 添加参考信息到消息下方
                                $(`#${loadingMessageId}`).append(referencesHtml);
                                
                                // 添加点击事件处理
                                $(`#${loadingMessageId} .references-section`).on('click', function() {
                                    $(this).toggleClass('expanded');
                                });
                            } else if (data.error) {
                                console.error("收到错误:", data.error);
                                $(`#${loadingMessageId}`).html(`错误: ${data.error}`);
                                eventSource.close();
                            }
                        } catch (e) {
                            console.error('解析消息时出错:', e, event.data);
                            if (event.data === '[DONE]') {
                                eventSource.close();
                                return;
                            }
                        }
                    };
                    
                    eventSource.onerror = function(error) {
                        console.error('EventSource错误:', error);
                        eventSource.close();
                        if (!responseText) {
                            $(`#${loadingMessageId}`).html('抱歉，处理您的请求时出现错误。请稍后再试。');
                        }
                    };
                    
                    // 添加超时处理
                    setTimeout(function() {
                        if (eventSource.readyState !== 2) { // 2 = CLOSED
                            eventSource.close();
                            if (!responseText) {
                                $(`#${loadingMessageId}`).html('请求超时，请稍后再试。');
                            }
                        }
                    }, 30000); // 30秒超时
                    
                } catch (error) {
                    console.error('创建EventSource时出错:', error);
                    $(`#${loadingMessageId}`).html('抱歉，无法建立连接。请稍后再试。');
                }
            }
            
            // 添加消息到聊天窗口
            function appendMessage(role, content, messageId = '') {
                const messageClass = role === 'user' ? 'user-message' : 'assistant-message';
                const avatarClass = role === 'user' ? 'user-avatar' : 'assistant-avatar';
                const icon = role === 'user' ? '<i class="bi bi-person"></i>' : '<i class="bi bi-robot"></i>';
                
                const messageHtml = `
                    <div class="message ${messageClass}" ${messageId ? `id="${messageId}"` : ''}>
                        <div class="message-avatar ${avatarClass}">
                            ${icon}
                        </div>
                        ${content}
                    </div>
                `;
                
                $('#chatContainer').append(messageHtml);
                $('#chatContainer').scrollTop($('#chatContainer')[0].scrollHeight);
                
                // 为新添加的参考信息添加点击事件
                if(messageId) {
                    $(`#${messageId} .references-section`).on('click', function() {
                        $(this).toggleClass('expanded');
                    });
                }
            }
            
            // 发送按钮点击事件
            $('#sendButton').on('click', sendMessage);
            
            // 输入框回车事件
            $('#userInput').on('keypress', function(e) {
                if (e.which === 13) {
                    sendMessage();
                }
            });
            
            // 模型切换
            $('.model-switch').on('click', function(e) {
                e.preventDefault();
                const modelType = $(this).data('model');
                if (modelType === currentModel) return;
                
                $.ajax({
                    url: '/api/switch-model',
                    type: 'POST',
                    data: { model_type: modelType },
                    success: function(response) {
                        if (response.success) {
                            currentModel = modelType;
                            const modelName = modelType === 'local' ? '本地模型' : '第三方模型';
                            appendMessage('assistant', `已切换到${modelName}`);
                        } else {
                            appendMessage('assistant', '模型切换失败: ' + (response.error || '未知错误'));
                        }
                    },
                    error: function(xhr) {
                        appendMessage('assistant', '模型切换请求失败: ' + xhr.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>
